//
//  RFAdInterstitial.swift
//  RFAds
//
//  Created by Roffa Zhou on 2024/12/26.
//

import Foundation
import GoogleMobileAds


//插页式广告先放这里
public class RFAdInterstitial: NSObject {
    public static let shared = RFAdInterstitial()
    fileprivate var interstitial: InterstitialAd?  //插页广告
    public var adId: String = "ca-app-pub-3940256099942544/4411468910"    //开屏广告App id, 默认不传使用测试id

    public var isLoadingAd = false   //是否正在加载广告
    public var isShowingAd = false     //是否正在显示广告，此时插页页显示在页面中
    public private(set) var loadCount: Int = 0       //app生命周期内，加载广告的次数, 只要发起了load就算一次
    public private(set) var loadedCount: Int = 0       //app生命周期内，加载广告成功的次数
    public private(set) var showCount: Int = 0       //app生命周期内，显示过广告的次数
    
    public func loadInterstitialAd(){
        Task {
              do {
                  isLoadingAd = true
                  loadCount += 1
                interstitial = try await InterstitialAd.load(
                    with: adId, request: Request())
                interstitial?.fullScreenContentDelegate = self
                  isLoadingAd = false
                  loadedCount += 1

                  RFAdmobUtils.postInterstitialLoadedNotif()
              } catch {
                  RFAdmobUtils.postInterstitialLoadeErrNotif(error as NSError)
                  isLoadingAd = false
              }
            }
    }
    @discardableResult
    public func showInterstitialAd(_ vc: UIViewController) -> Bool{
        if let ad = self.interstitial {
            isShowingAd = true
            ad.present(from: vc)
            return true
        } else {
          return false
        }
    }
    ///是否有已加载成功，但是未显示的广告
    public func hasLoaded() -> Bool {
        return interstitial != nil
    }
}

extension RFAdInterstitial:  FullScreenContentDelegate {
    public func adWillPresentFullScreenContent(_ ad: FullScreenPresentingAd) {
        showCount += 1
        RFAdmobUtils.postInterstitialShowedNotif()

    }
    public func adDidDismissFullScreenContent(_ ad: FullScreenPresentingAd) {

        interstitial = nil
        isShowingAd = false
        RFAdmobUtils.postInterstitialDismissNotif()

        
    }
    public func adWillDismissFullScreenContent(_ ad: FullScreenPresentingAd) {
        RFAdmobUtils.postInterstitialWillDismissNotif()

    }
    public func ad(
      _ ad: FullScreenPresentingAd,
      didFailToPresentFullScreenContentWithError error: Error
    ) {

      isShowingAd = false
        interstitial = nil
        RFAdmobUtils.postInterstitialShowErrNotif(error as NSError)

    }

}

